package com.primal.server;

import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Author whh
 * Date 2023/10/12/ 21:58
 * <p></p>
 */
public class ServerImpl {

    public static void main(String[] args) throws Exception {

        Server server = new Server(8888);


        //servlet服务
        ServletHandler servletHandler = new ServletHandler(){{

            addServletWithMapping(new ServletHolder(new HttpServlet() {
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                    resp.setContentType("text/html; charset=utf-8");
                    resp.setStatus(HttpServletResponse.SC_OK);
                    PrintWriter out = resp.getWriter();
                    out.println("<h1>" + "hello" + "</h1>");
                }

                @Override
                protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                    super.doPost(req, resp);
                }
            }),"/hello");
        }};

        AbstractHandler abstractHandler = new AbstractHandler() {
            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                response.setContentType("text/html; charset=utf-8");
                response.setStatus(HttpServletResponse.SC_OK);
                PrintWriter out = response.getWriter();
                out.println("<h1>" + "hello" + "</h1>");
                baseRequest.setHandled(true);

            }
        };

        //文件服务
        ResourceHandler resourceHandler = new ResourceHandler() {{
            setDirectoriesListed(true);
            setWelcomeFiles(new String[]{"index.html"});
            setResourceBase(".");
        }};


        HandlerList handlers = new HandlerList();
        handlers.setHandlers(new Handler[] { resourceHandler, servletHandler });
        server.setHandler(handlers);

        server.start();
        server.join();
    }
}
